package com.bright.controller.admin;

import com.bright.pojo.Tag;
import com.bright.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class TagController {

    @Autowired
    private TagService tagService;

    @CrossOrigin
    @GetMapping("/tags")
    public Page<Tag> getallTag(@PageableDefault(size = 8,sort = {"id"},direction = Sort.Direction.DESC) Pageable pageable){
        return tagService.getTags(pageable);
    }

    @CrossOrigin
    @PostMapping("/tag/input")
    public Tag inputTag(String tagname){
        Tag gettag = tagService.getTagByName(tagname);
        if (gettag!=null){
            System.out.println("添加失败");
            return null;
        }
        Tag t = new Tag();
        t.setName(tagname);
        return tagService.saveTag(t);
    }


    @CrossOrigin
    @PostMapping("/tag/update")
    public Tag updateTag(long id,String tagname){
        Tag tag = tagService.getTag(id);
        if (tag!=null){
            tag.setName(tagname);
            return tagService.saveTag(tag);
        }else {
            return null;
        }
    }

    @CrossOrigin
    @PostMapping("tag/delete")
    public String deleteTag(long id){
        tagService.delete(id);
        return "删除成功";
    }

}
